package com.tzbank.filter;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.tzbank.consumer.CommonServiceScheduler;
import com.tzbank.entity.UserParam;

/**
 * @author youkun
 *   验证token
 */
//@Component
public class TokenFilter extends ZuulFilter{


    @Autowired
    private CommonServiceScheduler commonServiceScheduler;

    /**
     * pre 可以在请求被路由之前调用
     * route 在路由请求时被调用
     * post 在route和error过滤之后被调用
     * error 处理请求时发生错误时被调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";   //请求路由前调用
    }

    @Override
    public int filterOrder() {
        return 0;   //执行顺序 数字越大级别越低
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if(!request.getRequestURI().contains("/logon") && !request.getRequestURI().contains("/checkToken")){
            //设置编码
            ctx.getResponse().setCharacterEncoding("UTF-8");
            UserParam userParam = new UserParam();
            try {
             String param  = StreamUtils.copyToString((InputStream) request.getInputStream(), Charset.forName("UTF-8"));
              userParam = (UserParam) JSON.parseObject(param,UserParam.class);
            } catch (IOException e) {
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code","-1");
                map.put("msg",e.getMessage());
                ctx.setResponseBody(JSON.toJSONString(map));
                return null;
            }
            //j校验token
            Map result = commonServiceScheduler.checkToken(userParam);
            if(!result.get("code").equals("200")){
                ctx.setSendZuulResponse(false);
                ctx.setResponseBody(JSON.toJSONString(result));
            }
        }
        return null;
    }
}
